#include "bsp_uart.h"
#include "bsp_init.h"
#include "bsp_led.h"

void uart1_io_init(void){
    IOMUXC_SetPinMux(IOMUXC_UART1_TX_DATA_UART1_TX, 0);
    IOMUXC_SetPinMux(IOMUXC_UART1_RX_DATA_UART1_RX, 0);
    IOMUXC_SetPinConfig(IOMUXC_UART1_TX_DATA_UART1_TX, 0x10B0);
    IOMUXC_SetPinConfig(IOMUXC_UART1_RX_DATA_UART1_RX, 0x10B0);
}

void uart_init(UART_Type* UARTx){

    uart1_io_init();

//关闭UART1
    UARTx->UCR1 &= ~(1<<0);	

//软件复位UART
    UARTx->UCR2 &= ~(1<<0);
    while((UARTx->UCR2 & 0x1) == 0);
//清零UART
    UARTx->UCR1 = 0;
//初始化UART
    UARTx->UCR2 = 0x5827;
    UARTx->UCR3 = 0x0004;

//设置波特率
    UARTx->UFCR = 5<<7;
    UARTx->UBIR = 71;
    UARTx->UBMR = 3124;


//使能UART
    UARTx->UCR1 |= (1<<0); 

}

void uart_write_char(UART_Type* UARTx ,  char *CHAR){

	while(((UARTx->USR2 >> 3) &0X01) == 0);/* 等待上一次发送完成 */
	UARTx->UTXD = *CHAR; 				/* 发送数据 */

}

char uart_read_char(UART_Type* UARTx ){

    char CHAR;
	while((UARTx->USR2 & 0x1) == 0);/* 等待接收完成 */
	CHAR =  (UARTx->URXD);			/* 返回接收到的数据 */
    return CHAR;

}

void uart_write_spring(UART_Type* UARTx ,  char *CHAR){
    
    char *p = CHAR;
    char b = '\r';
    char a = '\n';
    while(*p){
        uart_write_char(UARTx , p);
        p++;
    }
    uart_write_char(UARTx , &b);
    uart_write_char(UARTx , &a);


        
}


void uart1_int_init(void *usrparam){

    /*使能GIC中断号*/
    GIC_EnableIRQ(UART1_IRQn);

    /*注册gpio中断服务函数*/
    system_register_irqhandler(UART1_IRQn , uart1_irqhandler, usrparam);

    /*使能uart1的WAKE中断*/
    UART1->UCR4 |= (1<<7);

}

void uart1_irqhandler(unsigned int gicciar, void* param){

    //验证是否uart1的WAKE中断
    if( ((UART1->USR2 >> 7) & 0X01) == 1){
        char test[255];
        unsigned char num = 0;
        for(num=0;num<255;num++){
            test[num] = 0;
        }
        num = 0;
        //等待RXD上的数据传输完毕
        while( (((UART1->USR1)>>6) & 0x01) == 0 );
        //开始读数据，直到把RxFIFO中的数据全部读完
        while( (((UART1->UTS)>>5) & 0x01) == 0 ){
            test[num] = uart_read_char(UART1);
            num++;
            //由于寄存器UTS[5]位在读取数据后有波动，因此启用计时器等待该位稳定。
            EPIT1->CR |= (1<<0); 
            while ( ((EPIT1->SR) & 0X01) == 0 );
            EPIT1->CR &= ~(1<<0); 
            EPIT1->SR |= (1<<0);  
        }
        for(num=0 ; num<255 ; num++){
            *(char*)param = test[num];
            (char*)param++;
        } 
    }
    
    //清除中断标志
    UART1->USR2 |= (1<<7);
}

 void putc(unsigned char c){
    ;
 }
 unsigned char getc(void){
    ;
 }

 int raise(void){
    ;
 }